package com.spzx.common.rabbit.config;

import com.alibaba.fastjson2.JSON;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 服务器启动时，执行rabbitTemplate初始化，设置确认函数和回退函数
 * ApplicationEvent      一些子事件的父类。
 * ApplicationReadyEvent 具体子事件。表示应用程序启动好，IOC容器初始化好，存在相关bean对象了。再进行相关的初始化。
 * 也可以使用相关的注解替代： @EventListener
 */
@Slf4j
@Component
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setUpInitRabbitTemplete();
    }


    private void setUpInitRabbitTemplete() {
        //注册确认回调函数：交换机收没收到消息，都会执行回调处理。
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                //消息到交换器成功
                log.info("消息发送到Exchange成功：{}", correlationData);
            } else {
                //消息到交换器失败
                log.error("消息发送到Exchange失败：{}", cause);

                //执行消息重发
                this.retrySendMsg(correlationData);
            }
        });

        //注册回退回调函数：交换机收到了，但是没有找到匹配队列，回退给生产者
        rabbitTemplate.setReturnsCallback(returned -> {
            log.error("Returned: " + returned.getMessage() + "\nreplyCode: " + returned.getReplyCode()
                    + "\nreplyText: " + returned.getReplyText() + "\nexchange/rk: "
                    + returned.getExchange() + "/" + returned.getRoutingKey());

            System.out.println("returned = " + returned);

            //注意：关联数据没有完整退回，只是在请求消息头信息中回退关联数据的id.根据id从缓存中获取关联数据，进行重发消息。
            //String msg = new String(returned.getMessage().getBody());
            String correlationId = returned.getMessage().getMessageProperties().getHeader("spring_returned_message_correlation");
            String correlationDataStr = (String) redisTemplate.opsForValue().get(correlationId);
            GuiguCorrelationData guiguCorrelationData = JSON.parseObject(correlationDataStr, GuiguCorrelationData.class);

            if(guiguCorrelationData.isDelay()){
                //延迟消息不在进行消息重发。
                return;
            }

            //执行消息重发
            this.retrySendMsg(guiguCorrelationData);
        });
    }

    //用于消息重发
    private void retrySendMsg(CorrelationData correlationData) {
        System.out.println("retrySendMsg - correlationData = " + correlationData);
        GuiguCorrelationData guiguCorrelationData = (GuiguCorrelationData) correlationData;

        int retryCount = guiguCorrelationData.getRetryCount();
        if (retryCount >= 3) {
            log.info("消息最大重试次数不能大于3");
            return;
        }

        retryCount++;
        guiguCorrelationData.setRetryCount(retryCount);
        redisTemplate.opsForValue().set(correlationData.getId(), JSON.toJSONString(guiguCorrelationData),10, TimeUnit.MINUTES);

        if(guiguCorrelationData.isDelay()){ //延迟消息重发
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),
                    guiguCorrelationData.getRoutingKey(),
                    guiguCorrelationData.getMessage(),
                    message -> {
                        message.getMessageProperties().setDelay(guiguCorrelationData.getDelayTime()*1000);
                        return message;
                    },
                    guiguCorrelationData);
        }else{ //普通消息重发
            //先保存缓存再重发消息。重发消息依然携带关联数据，下次重发消息时还需要使用。
            rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),
                    guiguCorrelationData.getRoutingKey(),
                    guiguCorrelationData.getMessage(),
                    guiguCorrelationData);
        }


    }


}
